package com.life.ai.server.framework.desensitize;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.util.Objects;

/**
 * 脱敏序列化
 * DesensitizationSerialize
 *
 * @author kylewka
 * @since 2023/11/22
 */
@NoArgsConstructor
@AllArgsConstructor
public class DesensitizeJsonSerializer extends JsonSerializer<String> implements ContextualSerializer {

    private DesensitizeStrategy strategy;

    private Integer startInclude;

    private Integer endExclude;

    @Override
    public void serialize(String str, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        // 在序列化时进行数据脱敏
        if (DesensitizeStrategy.CUSTOMER.equals(strategy)) {
            jsonGenerator.writeString(StrUtil.hide(str, startInclude, endExclude));
        } else {
            jsonGenerator.writeString(strategy.desensitize().apply(str));
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        Desensitize annotation = beanProperty.getAnnotation(Desensitize.class);
        if (Objects.nonNull(annotation) && Objects.equals(String.class, beanProperty.getType().getRawClass())) {
            return new DesensitizeJsonSerializer(annotation.strategy(), annotation.start(), annotation.end());
        }
        return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
    }
}
